package com.yami.shop.im.socket;

import cn.hutool.core.util.StrUtil;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.Json;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.im.constants.Constant;
import com.yami.shop.im.constants.MsgCode;
import com.yami.shop.im.constants.SendType;
import com.yami.shop.im.hanlder.SecurityHandler;
import com.yami.shop.im.param.MessageInfo;
import com.yami.shop.im.vo.MsgItem;
import com.yami.shop.security.multishop.model.YamiShopUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Lzk
 */
@ServerEndpoint("/im/websocket/online/shop/{token}/{shopId}/{employeeId}")
@Component
@Slf4j
public class ShopOnlineWebSocketServer {

    /**
     * shopId为key
     */
    public static final ConcurrentHashMap<String, Session> SHOP_ONLINE_EMPLOYEE_MAP = new ConcurrentHashMap<>(256);

    private static SecurityHandler securityHandler;

    public static void setApplicationContext(ApplicationContext applicationContext) {
        securityHandler = applicationContext.getBean(SecurityHandler.class);
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws IOException {
        log.info("创建连接");
        YamiShopUser shopUser = securityHandler.getShopUser(token);
        if (shopUser == null) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CAN_NOT_FIND_USER_INFO, "无法获取用户信息")));
            }
            return;
        }

        // 如果原来就有token
        Session oldSession = SHOP_ONLINE_EMPLOYEE_MAP.get(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + Constant.UNDERLINE + shopUser.getEmployeeId() + Constant.UNDERLINE + token);
        if (oldSession != null) {
            // 客户端收到11，关闭ws链接，弹出提示
            if (oldSession.isOpen()) {
                oldSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.LOGIN_IN_OTHER_PLACE, "账户已在别处登录，请刷新")));
                oldSession.close();
            }
        }

        Set<String> set = RedisUtil.keys(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + Constant.UNDERLINE + "*");
        if (set.isEmpty()) {
            Set<String> set2 = UserWebSocketServer.USER_MAP.keySet();
            if (!set2.isEmpty()) {
                MsgItem msgItem = new MsgItem();
                msgItem.setChatType(SendType.SHOP);
                msgItem.setShopId(shopUser.getShopId());
                msgItem.setOnlineOrOffline(true);
                for (String key : set2) {
                    Session userSession = UserWebSocketServer.USER_MAP.get(key);
                    if (Objects.nonNull(userSession)) {
                        if (userSession.isOpen()) {
                            userSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.ONLINE_OR_OFFLINE, msgItem)));
                        }
                    }
                }
            }
        }

        SHOP_ONLINE_EMPLOYEE_MAP.put(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + Constant.UNDERLINE + shopUser.getEmployeeId() + Constant.UNDERLINE + token, session);
        RedisUtil.set(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + shopUser.getShopId() + Constant.UNDERLINE + shopUser.getEmployeeId() + Constant.UNDERLINE + token, "", 0);
        if (session.isOpen()) {
            session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success()));
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("token") String token, @PathParam( "shopId") Long shopId, @PathParam( "employeeId") Long employeeId) throws IOException {
        log.info("关闭连接");
        SHOP_ONLINE_EMPLOYEE_MAP.remove(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + shopId + Constant.UNDERLINE + employeeId + Constant.UNDERLINE + token);
        RedisUtil.del(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + shopId + Constant.UNDERLINE + employeeId + Constant.UNDERLINE + token);

        Set<String> set = RedisUtil.keys(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + shopId + Constant.UNDERLINE + "*");
        if (set.isEmpty()) {
            Set<String> set2 = UserWebSocketServer.USER_MAP.keySet();
            if (!set2.isEmpty()) {
                MsgItem msgItem = new MsgItem();
                msgItem.setChatType(SendType.SHOP);
                msgItem.setShopId(shopId);
                msgItem.setOnlineOrOffline(false);
                for (String key : set2) {
                    Session userSession = UserWebSocketServer.USER_MAP.get(key);
                    if (Objects.nonNull(userSession)) {
                        if (userSession.isOpen()) {
                            userSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.ONLINE_OR_OFFLINE, msgItem)));
                        }
                    }
                }
            }
        }
    }

    /**
     * 连接错误调用的方法
     */
    @OnError
    public void onError(Session session, @PathParam("token") String token, Throwable error, @PathParam( "shopId") Long shopId, @PathParam( "employeeId") Long employeeId) throws IOException {
        log.error("发生错误");
        error.printStackTrace();
        SHOP_ONLINE_EMPLOYEE_MAP.remove(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + shopId + Constant.UNDERLINE + employeeId + Constant.UNDERLINE + token);
        RedisUtil.del(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + shopId + Constant.UNDERLINE + employeeId + Constant.UNDERLINE + token);

        Set<String> set = RedisUtil.keys(Constant.ONLINE_SHOP_EMPLOYEE_PREFIX + shopId + Constant.UNDERLINE + "*");
        if (set.isEmpty()) {
            Set<String> set2 = UserWebSocketServer.USER_MAP.keySet();
            if (!set2.isEmpty()) {
                MsgItem msgItem = new MsgItem();
                msgItem.setChatType(SendType.SHOP);
                msgItem.setShopId(shopId);
                msgItem.setOnlineOrOffline(false);
                for (String key : set2) {
                    Session userSession = UserWebSocketServer.USER_MAP.get(key);
                    if (Objects.nonNull(userSession)) {
                        if (userSession.isOpen()) {
                            userSession.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.ONLINE_OR_OFFLINE, msgItem)));
                        }
                    }
                }
            }
        }
    }

    /**
     * 收到客户端消息后调用的方法，该消息由商家发过来
     *
     * @param sourceMessage 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String sourceMessage, @PathParam("token") String token, Session session) throws IOException {
        YamiShopUser shopUser = securityHandler.getShopUser(token);
        if (Objects.isNull(shopUser)) {
            log.error("无法获取用户信息");
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CAN_NOT_FIND_USER_INFO, "无法获取用户信息")));
            }
            return;
        }

        if (StrUtil.isBlank(sourceMessage)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CONTENT_FORMAT_ERROR, "内容格式有误")));
            }
            return;
        }

        log.info("sourceMessage: " + sourceMessage);

        MessageInfo messageInfo = Json.parseObject(sourceMessage, MessageInfo.class);

        if (Objects.isNull(messageInfo)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.fail(MsgCode.CONTENT_FORMAT_ERROR, "内容格式有误")));
            }
            return;
        }

        // 保持心跳
        if (StrUtil.equals(messageInfo.getContent(), Constant.HEART_BEAT)) {
            if (session.isOpen()) {
                session.getBasicRemote().sendText(Json.toJsonString(ServerResponseEntity.success(MsgCode.HEART_BEAT, "保持心跳")));
            }
            return;
        }

    }

}
